﻿package cn.poco.pepsi.activity.search;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import cn.poco.pepsi.R;
import cn.poco.pepsi.Service_impl.impl.SearchImpl;
import cn.poco.pepsi.activity.BaseActivity;
import cn.poco.pepsi.activity.search.thread.SearchUtil;
import cn.poco.pepsi.adapter.SearchResAdapter;
import cn.poco.pepsi.bean.Area;
import cn.poco.pepsi.bean.Dish;
import cn.poco.pepsi.bean.Restaurant;
import cn.poco.pepsi.constants.Constants;
import cn.poco.pepsi.dao.CacheDbService;
import cn.poco.pepsi.testActivity.TabTest;
import cn.poco.pepsi.util.GpsLocationUtil;
import cn.poco.pepsi.util.MyProgressDialog;

public class SearchResActivity extends BaseActivity {
	
	/**
	 * 
	 * 此类是餐厅列表，界面头有筛选功能按键
	 * 
	 * 
	 * 
	 * */
	
	

	private final static String TAG = "SearchResActivity";
	private final static int UPDATE_AREA = 100;
	private final static int UPDATE_SUB_AREA = 101;
	private final static int GET_RES_SUCCESS = 102;
	private final static int UPDATE_DATA = 103;
	private final static int UPDATE_DISH = 104;
	/** 商区代码 **/
	private String circleCode;
	private ArrayList<Restaurant> restaurant;
	private ListView listview;
	private SearchResAdapter adapter;//用于填充餐厅列表的信息
	private Handler hThread;
	private LinearLayout progressbar;
	private ProgressDialog dialog;
	private TextView noresult;
	private ImageButton refresh;
	/** 筛选条件 **/
	private Spinner spinner, filterdistance, filterbtn, filterarea;
	private FrameLayout filterbtnFrame;
	private List<Dish> dishs;
	private LinearLayout selectbar;
	private String maincitycode, mainkey, dish_id;
	private Boolean flag = false;
	private Boolean allFlag = false;
	private int currItem;
	private String mTitle = "";
	private Button setBtn;

	/** GPS数据 **/
	private Bundle bundle;
	private double lat, lon;
	private LinearLayout stopGps;
	private Button reload;
	private String gps_citycode;

	// 错误处理
	private LinearLayout error;

	// 分页信息
	private Boolean first; // 0首次进入
	private int CURRENT_PAGE = 0; // 当前页
	private LayoutInflater myInflater;
	private LinearLayout page;

	// 用户是否终止线程
	private Boolean flagThread = false;

	// 城市区域
	private List<Area> areaData, areaSubData;
	private ArrayAdapter<String> areaAdapter;

	// top100
	private TextView showTitle;

	private FrameLayout showBar;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		if (getIntent().getExtras().containsKey(Constants.TOP_RANK)) {
			this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		}
		myInflater = LayoutInflater.from(this);
		page = (LinearLayout) myInflater.inflate(R.layout.page, null);
		super.onCreate(savedInstanceState);
		first = true;
		CURRENT_PAGE = 0;
		setContentView(R.layout.search_restaurant);
		this.setTitle(getIntent().getExtras().getString(Constants.ACTIVITY_TOP_TITLE));
		stopGps = (LinearLayout) findViewById(R.id.stop_gps);
		reload = (Button) findViewById(R.id.reload);
		listview = (ListView) findViewById(R.id.listview);
		noresult = (TextView) findViewById(R.id.no_result);
		progressbar = (LinearLayout) findViewById(R.id.progressbar);
		showBar = (FrameLayout) findViewById(R.id.show_bar);
		spinner = (Spinner) findViewById(R.id.spinner);
		filterdistance = (Spinner) findViewById(R.id.filterdistance);
		filterbtn = (Spinner) findViewById(R.id.filterbtn);
		selectbar = (LinearLayout) findViewById(R.id.selectBar);
		filterarea = (Spinner) findViewById(R.id.areaspanner);
		filterbtnFrame = (FrameLayout) findViewById(R.id.filterbtnFrame);
		refresh = (ImageButton) findViewById(R.id.refresh);
		setBtn = (Button) findViewById(R.id.setnet);
		error = (LinearLayout) findViewById(R.id.error);
		Button reBtn = (Button) findViewById(R.id.tautology);

		reBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				progressbar.setVisibility(View.VISIBLE);
				error.setVisibility(View.GONE);
				startGetData();
			}
		});

		filterbtnFrame.setVisibility(View.VISIBLE);
		filterbtn.setVisibility(View.VISIBLE);
		spinner.setVisibility(View.VISIBLE);
		listview.setCacheColorHint(0);
		if (getIntent().getExtras().containsKey(Constants.TOP_RANK)) {
			showBar.setVisibility(View.VISIBLE);
			selectbar.setVisibility(View.GONE);
			showTitle = (TextView) findViewById(R.id.show_title);
			showTitle.setText(getIntent().getExtras().getString(Constants.RANK_NAME));
		}
		restaurant = new ArrayList<Restaurant>();

		ArrayAdapter<String> areaAdapter = new ArrayAdapter<String>(SearchResActivity.this, R.layout.spinner);
		areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		areaAdapter.add("500米");
		areaAdapter.add("1000米");
		areaAdapter.add("2000米");
		filterdistance.setAdapter(areaAdapter);
		ArrayAdapter<String> otherAdapter = new ArrayAdapter<String>(SearchResActivity.this, R.layout.spinner2);
		otherAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		otherAdapter.add("全部");
		otherAdapter.add("加盟");
		otherAdapter.add("优惠");
		filterbtn.setAdapter(otherAdapter);

		spinner.setOnItemSelectedListener(new SpinnerListener());
		filterbtn.setOnItemSelectedListener(new SpinnerListener());
		filterdistance.setOnItemSelectedListener(new SpinnerListener());
		filterarea.setOnItemSelectedListener(new SpinnerAreaListener());
		listview.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
				final String currId = String.valueOf(id);
				Intent intent = new Intent(SearchResActivity.this, TabTest.class);//ResTabActivity.class改为TabActivity
				if (position < restaurant.size()) {
					final Restaurant currentRes = restaurant.get(position);
					Bundle bundle = new Bundle();
					bundle.putLong(Constants.RES_CODE, id);
					bundle.putString(Constants.RES_TITLE, currentRes.getTitle());
					bundle.putString(Constants.RES_STAR, currentRes.getStar());
					bundle.putString(Constants.RES_AVERAGE, currentRes.getAverage());
					bundle.putString(Constants.RES_DISH, currentRes.getDish());
					bundle.putString(Constants.RES_CIRCLE, currentRes.getArea());
					bundle.putString(Constants.RES_ADDRESS, currentRes.getAddress());
					bundle.putString(Constants.RES_TEL, currentRes.getTel());
					bundle.putString(Constants.RES_MAIN_DISH, currentRes.getMaindish());
					bundle.putString(Constants.RES_COMMENTS, String.valueOf(currentRes.getComment()));
					bundle.putString(Constants.RES_IMAGES, String.valueOf(currentRes.getBlog()));
					bundle.putString(Constants.RES_INTRO, currentRes.getIntro());
					bundle.putString(Constants.RES_LOCATION, currentRes.getLocation());
					bundle.putString(Constants.RES_JOIN, String.valueOf(currentRes.getVouch()));
					bundle.putString(Constants.RES_PEPSI, String.valueOf(currentRes.getPepsi()));
					bundle.putString(Constants.RES_DISCOUNT, String.valueOf(currentRes.getDiscount()));
					// 把浏览过的餐厅信息保存到数据库
					new Thread(new Runnable() {
						@Override
						public void run() {
							CacheDbService reviewDB = new CacheDbService(SearchResActivity.this);
							int column = reviewDB.checkReview(currId);
							if (column <= 0) {
								reviewDB.savereview(currId, currentRes.getTitle(), currentRes.getStar(), currentRes
										.getAverage(), currentRes.getDish(), currentRes.getArea(), currentRes
										.getAddress(), currentRes.getTel(), currentRes.getMaindish(), String
										.valueOf(currentRes.getComment()), String.valueOf(currentRes.getBlog()),
										currentRes.getIntro(), currentRes.getLocation(), String.valueOf(currentRes
												.getVouch()), String.valueOf(currentRes.getPepsi()), String
												.valueOf(currentRes.getDiscount()));
							}
						}
					}).start();
					intent.putExtras(bundle);
					startActivity(intent);
				} else {
					handler.sendEmptyMessage(Constants.NEXT_PAGE);
				}

			}

		});

		// 设置网络
		setBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
				startActivity(intent);

			}
		});

		// 无法定位刷新功能
		reload.setOnClickListener(new GpsRefresh());

		// 设置该activity所需参数
		setInitParams();
		// 线程
		HandlerThread handlerThread = new HandlerThread("mySearchThread");
		handlerThread.start();
		hThread = new Handler(handlerThread.getLooper());

		// 判断数据源，加载数据
		startGetData();
	}

	// GPS刷新
	private final class GpsRefresh implements OnClickListener {
		@Override
		public void onClick(View v) {
			CURRENT_PAGE = 0;
			restaurant.clear();
			stopGps.setVisibility(View.GONE);
			dialog = MyProgressDialog.show(SearchResActivity.this, "正在定位,请稍候...");
			dialog.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {

					GpsLocationUtil.getInstance(SearchResActivity.this).unRequestListener();
					if (lat == 0 || lon == 0)
						stopGps.setVisibility(View.VISIBLE);
				}
			});
			hThread.post(new Gps(handler));
		}
	}

	// 查询栏Spinner事件监听
	private final class SpinnerListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {
			if (position > 0 || first == false) {
				if (adapter != null) {
					CURRENT_PAGE = 0; // 筛选设置当前页为0
					if (!filterdistance.isShown()) {
						first = false; // 设置非首次进入
						dialog = MyProgressDialog.show(SearchResActivity.this, "正在筛选...");
						hThread.post(new GetResByCircleCode(true)); // 筛选商区
					} else {
						if (lat != 0 && lon != 0) {
							first = false;
							dialog = MyProgressDialog.show(SearchResActivity.this, "正在筛选...");
							hThread.post(new GetResByLocation(gps_citycode, lat, lon, true));// 根据gps信息筛选餐厅
						}
					}
				}

			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> adapter) {
		}
	}

	/**
	 * UI更新操作
	 */
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case GET_RES_SUCCESS:
				progressbar.setVisibility(View.GONE);
				adapter = new SearchResAdapter(SearchResActivity.this, restaurant, handler, listview);
				if (getIntent().getExtras().containsKey(Constants.TOP_RANK))
					adapter.setRankNum(true);
				isCreatePage(); // 分页
				listview.setAdapter(adapter);
				listview.setVisibility(View.VISIBLE);
				break;
			case Constants.NEXT_PAGE:
				first = false;
				dialog = MyProgressDialog.show(SearchResActivity.this, "正在加载...");
				CURRENT_PAGE = CURRENT_PAGE + 10;
				if (bundle.containsKey(Constants.TOP_RANK)) {
					hThread.post(new GetTopRes(first, maincitycode));
				} else if (bundle.containsKey(Constants.TOPIC_ID)) { // 觅食专题筛选
					hThread.post(new GetResByTid(bundle.getInt(Constants.TOPIC_ID), false));
				} else if (!filterdistance.isShown()) {
					hThread.post(new GetResByCircleCode(false));
				} else {
					hThread.post(new GetResByLocation(gps_citycode, lat, lon, false));
				}
				break;
			case UPDATE_DATA:
				isCreatePage(); // 是否分页
				if (adapter != null)
					adapter.notifyDataSetChanged();
				break;
			case UPDATE_DISH:
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchResActivity.this, R.layout.spinner);
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				adapter.add("全部菜式");
				for (int i = 0; i < dishs.size(); i++) {
					adapter.add(dishs.get(i).getName());
				}
				spinner.setAdapter(adapter);
				break;
			case Constants.GPS_LOCATION_CHANGE:
				dialog.setMessage("正在获取数据...");
				GpsLocationUtil.getInstance(SearchResActivity.this).unRequestListener();
				Bundle bundle = msg.getData();
				lat = bundle.getDouble(Constants.GPS_LAT);
				lon = bundle.getDouble(Constants.GPS_LONG);
				hThread.post(new GetResByLocation(gps_citycode, lat, lon, false));
				handler.removeMessages(msg.what);
				break;
			case Constants.STOP_GPS:
				GpsLocationUtil.getInstance(SearchResActivity.this).unRequestListener();
				if (dialog != null)
					dialog.dismiss();
				stopGps.setVisibility(View.VISIBLE);
				break;
			case Constants.NO_GPS:
				if (dialog != null)
					dialog.dismiss();
				new AlertDialog.Builder(SearchResActivity.this).setTitle("错误").setMessage("没有打开GPS设置,无法获取您的位置信息，现在开启?")
						.setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								startActivity(new Intent("android.settings.LOCATION_SOURCE_SETTINGS"));
							}
						}).show();
				break;
			case UPDATE_AREA:
				areaAdapter = new ArrayAdapter<String>(SearchResActivity.this, R.layout.spinner);
				areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
				for (int i = 0; i < areaData.size(); i++) {
					areaAdapter.add(areaData.get(i).getName());
				}
				filterarea.setAdapter(areaAdapter);
				filterarea.setSelection(0, true);
				filterarea.setPrompt("所有地区");
				break;
			case UPDATE_SUB_AREA:
				areaAdapter.clear();
				for (int i = 0; i < areaSubData.size(); i++) {
					areaAdapter.add(areaSubData.get(i).getName());
				}
				areaAdapter.notifyDataSetChanged();
				filterarea.setPrompt(areaSubData.get(1).getName());
				filterarea.setSelection(1, true);
				break;
			case Constants.CONN_ERROR:
				// TODO....
				break;
			}
		}

		// 是否分页
		private void isCreatePage() {
			try {
				listview.removeFooterView(page);
				if (!restaurant.isEmpty() && adapter != null) {
					noresult.setVisibility(View.GONE);
					if (restaurant.size() < restaurant.get(0).getTotal()) {
						page.setVisibility(View.VISIBLE);
						listview.addFooterView(page);
					}
				} else {
					noresult.setVisibility(View.VISIBLE);
				}
			} catch (Exception e) {
				Log.e(TAG, e.toString());
			}

		}
	};

	// 地区选择监听器
	private final class SpinnerAreaListener implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> adapter, View view, int position, long id) {

			String showTitle = filterarea.getPrompt().toString();
			if (showTitle.equals("所有地区")) {
				if (position > 0) {
					first = false;
					flag = false;
					allFlag = true;
					currItem = position;
					Area area = areaData.get(position);
					String areaId = area.getKey();
					hThread.post(new GetSubArea(areaId));
					dialog = MyProgressDialog.show(SearchResActivity.this, "正在加载...");
					circleCode = areaData.get(position).getKey();
					hThread.post(new GetResByCircleCode(true));
					filterarea.getItemAtPosition(position);
					mTitle = areaData.get(position).getName();
				}
			} else {
				if (position > 1) {
					flag = true;
					dialog = MyProgressDialog.show(SearchResActivity.this, "正在加载...");
					circleCode = areaSubData.get(position).getKey();
					hThread.post(new GetResByCircleCode(true));
					mTitle = areaSubData.get(position).getName();
				}
				if (position == 1 && flag) {
					dialog = MyProgressDialog.show(SearchResActivity.this, "正在加载...");
					circleCode = areaData.get(currItem).getKey();
					hThread.post(new GetResByCircleCode(true));
					mTitle = areaData.get(currItem).getName();
				}
				if (position == 0 && allFlag) {
					dialog = MyProgressDialog.show(SearchResActivity.this, "正在加载...");
					hThread.post(new GetArea());
					circleCode = "";
					hThread.post(new GetResByCircleCode(true));
					allFlag = false;
					mTitle = "全部地区";
					
				}
			}
			if (!first)
				if (mainkey != null && !mainkey.equals("")) {
					SearchResActivity.this.setTitle("关键字搜索：" + mainkey + "+" + mTitle);
				} else {
					SearchResActivity.this.setTitle(mTitle);
				}

		}

		@Override
		public void onNothingSelected(AdapterView<?> arg0) {
		}
	}

	// 设置该Activity参数
	private void setInitParams() {
		// 取参数
		bundle = getIntent().getExtras();
		if (bundle.containsKey(Constants.CIRCLE_CODE)) {
			circleCode = bundle.getString(Constants.CIRCLE_CODE);
		} else {
			mainkey = bundle.getString(Constants.SEARCH_CONTENT);
			if (mainkey != null && !mainkey.equals(""))
				this.setTitle("关键字搜索：" + mainkey);
		}
		maincitycode = bundle.getString(Constants.CITY_CODE);
	}

	// 判断数据源，加载数据
	private void startGetData() {
		// 取菜单
		CacheDbService dishservice = new CacheDbService(SearchResActivity.this);
		if (dishservice.checkDish(maincitycode) > 0) {
			dishs = dishservice.find(maincitycode);
			handler.sendEmptyMessage(UPDATE_DISH);
		} else {
			hThread.post(new GetDishs());
		}

		if (bundle.containsKey(Constants.TOP_RANK)) { // 排行榜TOP100
			spinner.setVisibility(View.GONE);
			filterbtn.setVisibility(View.GONE);
			hThread.post(new GetTopRes(first, maincitycode));
		} else if (bundle.containsKey(Constants.TOPIC_ID)) {
			selectbar.setVisibility(View.GONE); // 觅食专题
			hThread.post(new GetResByTid(bundle.getInt(Constants.TOPIC_ID), false));
		} else if (!bundle.containsKey(Constants.NEAR_MODULE)) {
			filterarea.setVisibility(View.VISIBLE); // 根据商区代码获取餐厅
			hThread.post(new GetResByCircleCode(false));
			CacheDbService db = new CacheDbService(this);
			Integer size = db.checkArea(maincitycode);
			if (size <= 0) {
				hThread.post(new GetArea()); // 获取筛选商区
			} else {
				areaData = db.getArea(maincitycode);
				handler.sendEmptyMessage(UPDATE_AREA);
			}
			filterarea.setPrompt("所有地区");
		} else {
			showBar.setVisibility(View.VISIBLE);
			filterdistance.setVisibility(View.VISIBLE);
			progressbar.setVisibility(View.GONE);
			refresh.setVisibility(View.VISIBLE);
			refresh.setOnClickListener(new GpsRefresh());
			// TODO...........
			SharedPreferences preferences = getSharedPreferences(Constants.GPS_CITY_CODE, Context.MODE_PRIVATE);
			if (preferences.contains(Constants.CITY_CODE)) {
				gps_citycode = preferences.getString(Constants.CITY_CODE, null);
			}
			dialog = MyProgressDialog.show(this, "正在定位,请稍候...");
			dialog.setOnDismissListener(new OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					GpsLocationUtil.getInstance(SearchResActivity.this).unRequestListener();
					if (lon == 0 || lat == 0)
						stopGps.setVisibility(View.VISIBLE);
				}
			});
			hThread.post(new Gps(handler));

		}
	}

	// 根据商区代码获取美食列表
	private final class GetResByCircleCode implements Runnable {
		private String dish, dis, vouch, dishid;
		private Boolean clear;

		public GetResByCircleCode(Boolean clear) {
			this.clear = clear;
			switch (filterbtn.getSelectedItemPosition()) {
			case 1:
				vouch = "1";
				break;
			case 2:
				dis = "1";
				break;
			}

			if (spinner.getSelectedItemPosition() > 0) {
				dishid = String.valueOf(dishs.get(spinner.getSelectedItemPosition() - 1).getId());
			}
			if (dish_id != null && !dish_id.equals("")) {
				dish = dish_id;
				dish_id = null;
			}
		}

		@Override
		public void run() {
			if (!flagThread) {
				try {
					restaurant = SearchUtil.getResByCircleCode(restaurant, maincitycode, CURRENT_PAGE, dis, vouch,
							null, dishid, mainkey, circleCode, dish, clear);
				} catch (Exception e) {
					Log.e(TAG, e.toString());
					progressbar.setVisibility(View.GONE);
					// error.setVisibility(View.VISIBLE);
					handler.sendEmptyMessage(Constants.CONN_ERROR);
					e.printStackTrace();
				}
				sendMsg(); // 发送消息
				if (dialog != null)
					dialog.dismiss();
			}
		}
	}

	// 根据GPS地理坐标获取餐厅列表
	private final class GetResByLocation implements Runnable {
		private double lat, lon;
		private int dis, vouch = 0;
		private long dishid = 0;
		private Float d = 0.5f;
		private Boolean clear;
		private String citycode;

		public GetResByLocation(String citycode, double lat, double lon, Boolean clear) {
			this.lat = lat;
			this.lon = lon;
			this.clear = clear;
			this.citycode = citycode;
			switch (filterbtn.getSelectedItemPosition()) {
			case 1:
				vouch = 1;
				break;
			case 2:
				dis = 1;
				break;
			}
			switch (filterdistance.getSelectedItemPosition()) {
			case 1:
				d = 1f;
				break;
			case 2:
				d = 2f;
				break;
			}
			if (spinner.getSelectedItemPosition() > 0) {
				dishid = dishs.get(spinner.getSelectedItemPosition() - 1).getId();
			}
		}

		@Override
		public void run() {
			if (!flagThread) {
				try {
					SearchUtil.getResByLocation(citycode, restaurant, clear, lat, lon, CURRENT_PAGE, dis, vouch,
							dishid, d);
				} catch (Exception e) {
					Log.e(TAG, e.toString());
					progressbar.setVisibility(View.GONE);
					// error.setVisibility(View.VISIBLE);
					handler.sendEmptyMessage(Constants.CONN_ERROR);
					e.printStackTrace();
				}
				sendMsg(); // 
				if (dialog != null)
					dialog.dismiss();
			}
		}
	}

	// 根据tid(专题ID)获取餐厅列表
	private final class GetResByTid implements Runnable {
		private int tid;
		private Boolean clear;

		public GetResByTid(int tid, Boolean clear) {
			this.tid = tid;
			this.clear = clear;
		}

		@Override
		public void run() {
			try {
				restaurant = SearchUtil.getTopicRes(String.valueOf(tid), CURRENT_PAGE, clear, restaurant);
			} catch (Exception e) {
				Log.e(TAG, e.toString());
				progressbar.setVisibility(View.GONE);
				// error.setVisibility(View.VISIBLE);
				handler.sendEmptyMessage(Constants.CONN_ERROR);
				e.printStackTrace();
			}
			sendMsg(); // 发送消息
			if (dialog != null)
				dialog.dismiss();
		}

	}

	// 获取TOP100餐厅
	private final class GetTopRes implements Runnable {
		private Boolean clear;
		private String citycode;

		public GetTopRes(Boolean clear, String citycode) {
			this.clear = clear;
			this.citycode = citycode;
		}

		@Override
		public void run() {
			try {
				restaurant = SearchUtil.getTopRes(citycode, CURRENT_PAGE, restaurant, clear);
			} catch (Exception e) {
				Log.e(TAG, e.toString());
				progressbar.setVisibility(View.GONE);
				// error.setVisibility(View.VISIBLE);
				handler.sendEmptyMessage(Constants.CONN_ERROR);
				e.printStackTrace();
			}
			sendMsg(); // 发送消息
			if (dialog != null)
				dialog.dismiss();
		}

	}

	// 获取菜式分类信息
	private final class GetDishs implements Runnable {
		@Override
		public void run() {
			if (!flagThread) {
				try {
					SearchImpl search = new SearchImpl();
					dishs = search.getDishs(maincitycode, "dish", SearchResActivity.this);
					handler.sendEmptyMessage(UPDATE_DISH);
				} catch (Exception e) {
					progressbar.setVisibility(View.GONE);
					// error.setVisibility(View.VISIBLE);
					Log.e(TAG, e.toString());
					e.printStackTrace();
				}
			}
		}
	}

	// 获取城市地区信息
	private final class GetArea implements Runnable {
		@Override
		public void run() {
			areaData = SearchUtil.getArea(SearchResActivity.this, maincitycode);
			handler.sendEmptyMessage(UPDATE_AREA);

		}
	}

	// 获取城市商区信息
	private final class GetSubArea implements Runnable {
		private String lid;

		public GetSubArea(String lid) {
			this.lid = lid;
		}

		@Override
		public void run() {
			areaSubData = SearchUtil.getSubArea(SearchResActivity.this, maincitycode, lid);
			handler.sendEmptyMessage(UPDATE_SUB_AREA);
		}
	}

	// 发送消息
	private void sendMsg() {
		if (first) {
			handler.sendEmptyMessage(GET_RES_SUCCESS);
			;
		} else {
			handler.sendEmptyMessage(UPDATE_DATA);
		}
	}

	// GPS定位
	private final class Gps implements Runnable {
		private Handler handler;

		public Gps(Handler handler) {
			this.handler = handler;
		}

		@Override
		public void run() {
			if (!flagThread) {
				GpsLocationUtil.getInstance(SearchResActivity.this).getLocation(handler);
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && !filterdistance.isShown()) {
			super.setFlag(false);
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
		flagThread = true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		flagThread = false;
	}

}
